//
//  OAuthViewController.swift
//  01-WeiBo
//
//  Created by 李晓东 on 17/6/29.
//  Copyright © 2017年 PeanutXu. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController {
    
    lazy var webView = UIWebView()
    override func loadView() {
        self.view = webView
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(OAuthViewController.backClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(autoInsert))
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self
//        self.webView.loadRequest(URLRequest(url: URL(string: "https://api.weibo.com/oauth2/authorize?client_id=3326606937&redirect_uri=http://www.baidu.com")!))
        
        self.webView.loadRequest(URLRequest(url: URL(string: NetWorkingTools.shareNetWorkingTools.oauthURL())!))
    }
    
    func backClick(){
        dismiss(animated: true, completion: nil)
    }
    
    func autoInsert() {
        let js = "document.getElementById('userId').value = '18507561078';" + "document.getElementById('passwd').value = '19890529lixd'"
        webView.stringByEvaluatingJavaScript(from: js)
    }

}

extension OAuthViewController:UIWebViewDelegate{
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.url , url.host == "www.baidu.com"  else {
            return true
        }
        
        guard let str = url.query ,str.hasPrefix("code=")  else {
            return false
        }
        
        let code = str.substring(from: "code=".endIndex)
//        UserAccountViewModel.shareUserAccount.loadUserAccessToken(code: code, finished: <#T##(Bool) -> ()#>)
        UserAccountViewModel.shareUserAccount.loadUserAccessToken(code: code) { (flag) in
            if flag {
                print("work")
            } else {
                print("failure")
            }
        }
//        NetWorkingTools.shareNetWorkingTools.loadAccessToken(code: code) { (result, error) in
//            if result != nil {
//                let account = UserAccount(params: result as! [String: Any])
//                print(account)
//                self.loadUserInfo(account: account)
//            } else {
//                
//            }
//        }
        
        return true
    }
}

//extension OAuthViewController{
//    func loadUserInfo(account: UserAccount)  {
//        NetWorkingTools.shareNetWorkingTools.loadUserInfo(accessToken: account.access_token!, uid: account.uid!) { (result, error) in
//            guard let r = result as? [String: Any] else {
//                return
//            }
//            account.saveUserAccount()
//        }
//    }
//}

//https://api.weibo.com/oauth2/authorize?client_id=3326606937&redirect_uri=http://www.baidu.com

